package com.zhenhao.xsq.data.api.support;

import android.content.Intent;
import android.util.Log;

import com.blankj.utilcode.util.ActivityUtils;
import com.zhenhao.xsq.application.AppConfig;
import com.zhenhao.xsq.data.api.API;
import com.zhenhao.xsq.ui.activity.login.LoginActivity;
import com.zhenhao.xsq.utils.HttpUtils;
import com.zhenhao.xsq.utils.SpSaveUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 自动刷新token的拦截器
 *
 * @author shijiacheng
 * @version 1.0
 */

public class TokenInterceptor implements Interceptor {

    private static final String TAG = "TokenInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        if (originalRequest.url().toString().contains(API.user_login)) {
            //登录接口不需要请求头 token
        } else if (originalRequest.url().toString().contains(API.user_xiangmu)) {
            //项目接口不需要请求头 token
        } else {
            originalRequest = originalRequest.newBuilder().addHeader("Authorization",
                    SpSaveUtils.getAccessToken()).build();
        }

        Response originalResponse = chain.proceed(originalRequest);
        // 获取返回的数据字符串
        ResponseBody responseBody = originalResponse.body();
        BufferedSource source = originalResponse.body().source();
        source.request(Integer.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF_8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset();
        }
        String bodyString = buffer.clone().readString(charset);
        //根据和服务端的约定判断token过期
        if (isTokenExpired(originalResponse, bodyString)) {
            try {
                Log.d(TAG, "自动刷新Token,然后重新请求数据");
                //同步请求方式，获取最新的Token
                String json = getNewToken();
                JSONObject jsonObject = new JSONObject(json);
                int code = jsonObject.get("code") == null ? 0 : (Integer) jsonObject.get("code");
                if (code == 200) {
                    String access_token = jsonObject.getString("data");
//                    String refresh_token = list.getString("refresh_token");
                    SpSaveUtils.putAccessToken(access_token);
//                    SpSaveUtils.putRefreshToken(refresh_token);
                    //使用新的Token，创建新的请求
                    Request newRequest = chain.request()
                            .newBuilder()
                            .header("Authorization",  access_token)
                            .build();
                    //重新请求
                    return chain.proceed(newRequest);
                } else if (code == 991) {
                    //回到登录界面
                    Intent intent = new Intent(AppConfig.getInstance(), LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    AppConfig.getInstance().startActivity(intent);
                    ActivityUtils.finishAllActivities();
                    SpSaveUtils.clearSp();
                    return originalResponse;
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return originalResponse;
            }

        }
        return originalResponse;
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response, String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            int code = jsonObject.getInt("code");
            if (response.code() == 200 && code == 993) {
                return true;
            }
            return false;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private String getNewToken() throws IOException {
        // 通过获取token的接口，同步请求接口
        Map<String, String> map = new HashMap<>();
//        map.put("grant_type", "refresh_token");
//        map.put("refresh_token", SpSaveUtils.getRefreshToken());
        String s = HttpUtils.refreshToken(API.BASE_URL + API.user_refresh, map);
        return s;
    }
}
